package com.youshang.designpattern.chain.handler;

import cn.hutool.core.collection.CollUtil;
import com.google.common.base.Supplier;

import java.lang.reflect.Type;
import java.util.Map;

public class ConstructHandle {

    private static Map<Type, Supplier<? extends HandleBase>> chainMap;

    public ConstructHandle(Map<Type, Supplier<? extends HandleBase>> chainMap){
        this.chainMap = chainMap;
    }


    /**
     * 通过处理器类型创建处理器
     *
     * @param type    处理器类型
     */
    public static HandleBase createHandler(Class<? extends HandleBase> ...type) {
        if (CollUtil.isEmpty(chainMap)) {
            throw new RuntimeException("当前chainMap为空，请检查是否存在初始化！！！");
        }
        if (type == null || type.length == 0) {
            throw new RuntimeException("当前责任链对象为空，请检查代码！！！");
        }
        if (type.length == 1) {
            HandleBase handleBase = chainMap.get(type[0]).get();
            handleBase.setHead(handleBase);
            handleBase.setTail(handleBase);
            return handleBase;
        }

        HandleBase handleBase = null;
        HandleBase previousHandleBase = null;

        for (int i = 0; i < type.length; i++) {
            handleBase = chainMap.get(type[i]).get();
            if (handleBase == null) {
                throw new RuntimeException("当前handleBase为空，key=__"+type[i].getName()+"__请检查是否存在当前方法的责任链配置！！！");
            }
            if (i == 0) {
                handleBase.setHead(handleBase);
                handleBase.setTail(handleBase);
            }else {
                previousHandleBase.setNext(handleBase);
                handleBase.setHead(previousHandleBase.getHead());
                handleBase.setTail(handleBase);
                handleBase.setPrevious(previousHandleBase);
            }
            previousHandleBase = handleBase;
        }
        return handleBase;
    }
}
